package com.mingzhi.loggingservice.consumer;

import com.mingzhi.loggingservice.entity.OperationLogs;
import com.mingzhi.loggingservice.mapper.OperationLogsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@RabbitListener(queues = "direct.shuzimali.queue")
public class OperationLogConsumer {

    @Autowired
    private OperationLogsMapper operationLogsMapper;

    @RabbitHandler
    public void processLog(OperationLogs operationLogs) {
        log.info("接收到消息：{}", operationLogs);
        // 解析消息并保存到数据库
        OperationLogs log = new OperationLogs();
        log.setUserId(operationLogs.getUserId());
        log.setAction(operationLogs.getAction());
        log.setIp(operationLogs.getIp());
        log.setDetail(operationLogs.getDetail());
        operationLogsMapper.insert(log);
    }

    private Long parseUserId(String message) {
        try {
            int start = message.indexOf("ID=") + 3;
            int end = message.indexOf(",", start);
            return Long.parseLong(message.substring(start, end));
        } catch (Exception e) {
            return null;
        }
    }

    private String parseAction(String message) {
        if (message.contains("注册")) {
            return "REGISTER";
        } else if (message.contains("升级")) {
            return "UPGRADE";
        } else if (message.contains("降级")) {
            return "DOWNGRADE";
        }
        return "UNKNOWN";
    }
}
